package com.timedomain.him.remake.ui;

import android.app.AlertDialog;
import android.app.Notification;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import com.timedomain.him.remake.Program;
import com.timedomain.him.remake.R;
import com.timedomain.him.remake.utils.AppSettings;
import com.timedomain.him.remake.utils.BaseActivity;
import com.timedomain.him.remake.utils.DB;
import com.timedomain.him.remake.utils.FileUtils;
import com.timedomain.him.remake.utils.MorningCallManager;
import com.timedomain.him.remake.utils.NotificationUtils;
import com.timedomain.him.remake.utils.TimeUtils;

import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class SettingActivity extends BaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
    }

    public void btnMorningCallTriggerMode(View view) {
        new AlertDialog.Builder(this)
                .setMessage("早安电话触发：\n" +
                        "旧版：不需要进行晚安对话\n" +
                        "新版：需要进行晚安对话并约定时间之后才会接到（凌晨四点之前）\n")
        .setPositiveButton("新版", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AppSettings.morningCallIsManual = true;
                AppSettings.saveSettings(SettingActivity.this);
                MorningCallManager.setNextMorningCall(SettingActivity.this);
            }
        }).setNegativeButton("旧版", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AppSettings.morningCallIsManual = false;
                AppSettings.morningCallDateStamp = TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone());
                AppSettings.saveSettings(SettingActivity.this);
                MorningCallManager.setNextMorningCall(SettingActivity.this);
            }
        }).create().show();
    }

    public void btnMorningCallSetTime(View view) {
        startActivity(new Intent(this,MorningCallActivity.class));
        finish();
    }

    public void btnNightModeDuration(View view) {
        final String[] items = new String[]{"20分钟","30分钟","45分钟","60分钟"};
        new AlertDialog.Builder(this).setTitle("晚安模式时长").setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int newMin = Integer.parseInt(items[which].replace("分钟",""));
                AppSettings.nightModeDuration = newMin;
                AppSettings.saveSettings(SettingActivity.this);
            }
        }).setNegativeButton("取消",null).create().show();
    }

    public void btnNightModeStoryCount(View view) {

        final String[] items = new String[]{"2个","3个","4个","5个"};
        new AlertDialog.Builder(this).setTitle("晚安模式故事数量").setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int newMin = Integer.parseInt(items[which].replace("个",""));
                AppSettings.nightModeStoryCount = newMin;
                AppSettings.saveSettings(SettingActivity.this);
            }
        }).setNegativeButton("取消",null).create().show();
    }

    public void btnNightModeExcludedStories(View view) {
        List<String> paths = FileUtils.getAllNightStories();
        String[] displayTitle = new String[paths.size()];
        boolean[] checkState = new boolean[paths.size()];

        for (int i = 0; i < paths.size(); i++) {

            displayTitle[i] = FileUtils.getFileNameWithoutExtension(paths.get(i));
            checkState[i] = AppSettings.filteredNightStories.contains(paths.get(i));
        }

        new AlertDialog.Builder(this).setTitle("选择晚安模式中不想要出现的故事").setMultiChoiceItems(displayTitle, checkState, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                checkState[which] = isChecked;
            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                List<String> toRemove = new ArrayList<>();
                for (int i = 0; i < checkState.length; i++) {
                    if(checkState[i]){
                        toRemove.add(paths.get(i));
                    }
                }
                if(toRemove.size() + 5 > paths.size()){
                    showToast("需要至少五个故事。");
                    return;
                }
                AppSettings.filteredNightStories.clear();
                AppSettings.filteredNightStories.addAll(toRemove);
                AppSettings.saveSettings(SettingActivity.this);
            }
        }).create().show();

    }

    public void btnAbout(View view) {
//        new AlertDialog.Builder(this).setTitle("他APP Remake")
//                .setMessage("「我想给他一个新的世界」\n\n" +
//                        "设计/图像资源/音乐：他APP（原版）\n" +
//                        "程序：ZYFDroid\n")
//                .setNegativeButton("关闭",null).create().show();
        startActivity(new Intent(this,AboutActivity.class));
    }

    public void btnLogoutClick(View view) {
        view.setEnabled(false);
        Animation a = AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right);
        a.setFillAfter(true);
        a.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        view.startAnimation(a);
    }

    public void showNotificationSettings(View view) {
        NotificationUtils.showNotificationSetting(this);
    }


    public void clearChatlog(View view) {
        new AlertDialog.Builder(this)
                .setMessage("是否清空聊天记录？")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DB.ChatMessage.Clear();
                        showToast("清理完成");
                    }
                }).setNegativeButton(android.R.string.no,null).create().show();
    }


    public void showBackgroundSettings(View view) {
        startActivity(new Intent(this,BackgroundActivateSettingsActivity.class));
    }

    public void btnNightModeVolumeAdjustment(View view) {
        final String[] items = new String[]{"15%","20% (降噪耳机)","25%","30%","40% (普通耳机，手机外放)","60%","75%","80%","100% (音响)"};
        new AlertDialog.Builder(this).setTitle("晚安模式呼吸声音量调整").setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                float newMin = Integer.parseInt(items[which].split(Pattern.quote("%"))[0]);
                AppSettings.nightModeVolumeAdjustment = newMin / 100f * 0.25f;
                AppSettings.saveSettings(SettingActivity.this);
            }
        }).setNegativeButton("取消",null).create().show();
    }

    public void btnNightModeBatteryOptimization(View view) {
        new AlertDialog.Builder(this)
                .setTitle("晚安模式省电设置：")
                .setMessage(
                        "开启省电时，若晚安模式中没有接入充电器，则晚安模式结束45分钟后会自动退出晚安模式。\n\n" +
                        "开启此功能可以防止忘记接入充电器时第二天早上手机没电的情况。\n\n" +
                        "如果您的手机电池特别庞大，或者正在使用安卓模拟器，可以关闭这个功能。")
                .setPositiveButton("开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AppSettings.nightModeIgnoreBattery = false;
                        AppSettings.saveSettings(SettingActivity.this);
                    }
                }).setNegativeButton("关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AppSettings.nightModeIgnoreBattery = true;
                AppSettings.saveSettings(SettingActivity.this);
            }
        }).create().show();
    }

}
